import type { Directive } from 'vue'

interface Argtyps{
        ele: HTMLElement,
        src:String
}
// 按钮权限
const loadlazyImg: Directive = {
    beforeMount(el:HTMLElement, binding) {
        let Vpage:any = document.querySelector('.vpage')   
        Vpage.addEventListener('scroll', () => {
            let isLazy = el.getAttribute('data-lazy')    
            if (!isLazy && isLazy == null || isLazy == undefined) {
                throttle(lazyImg({ ele: el, src: binding.value }), 1000)
            }
        })
    },
    // 初始化的时候判断图片是否在视口内
    mounted(el:HTMLElement, binding) {
        throttle(lazyImg({ ele: el, src: binding.value }), 2000)
    },
}
const lazyImg = (e:Argtyps) => {
    let ele = e.ele
    let url = e.src
    //   获取元素到顶部的距离
    let top = ele.getBoundingClientRect().top  
     
    //   获取浏览器视口宽度
    let windowHeight = window.innerHeight
    //   如果视口高度大于元素到顶部的距离时那需要做懒加载
    if (top + 10 < windowHeight) {
        setTimeout(() => {
            ele.src = url
        }, 1000)
        // 为了避免重复加载页面 data-lazy 为加载状态，不建议使用遍历，可能会造成内存泄露
        ele.setAttribute('data-lazy', true) 
    }
}
// 防抖
const throttle = function (fn, wait) {
    let timer:any = null
    return function (...args) {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
            timer = null
            fn.apply(this, args) 
        }, wait)
    }
}

export default loadlazyImg
/** 使用将需要加载的图片放入即可
 *  <img class="imgs"  v-lazyload="`https://img0.baidu.com/it/u=1079959710,2776870030&fm=26&fmt=auto`"  alt="">
 * 
 */